package com.utils;

import com.utils.base64.Base64Converter;

import java.io.BufferedInputStream;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.logging.Logger;

/*
 * 加密算法库
 */
public class Encryptions {
    public Encryptions() {}
    
    private static final char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9','a', 'b', 'c', 'd', 'e', 'f' };
	public static final String MD5 = "MD5";
	public static final String SHA_1 = "SHA1";
	private static final Logger logger = Logger.getLogger("");
    
	/**
	 * 获取文件流
	 * @param br
	 * @return
	 * @throws Exception
	 */
	public static byte[] getFileByte(BufferedInputStream br) throws Exception{
		byte[] cbuf = new byte[1024];
		byte[] fileByte = new byte[0];
		byte[] temp;
		int readLen = 0;
		int tmpoffset = 0;
		while((readLen = br.read(cbuf))>0){
			tmpoffset += readLen;
			temp = fileByte;
			fileByte = new byte[tmpoffset];
			System.arraycopy(temp, 0, fileByte, 0, temp.length);
			System.arraycopy(cbuf, 0, fileByte, temp.length, readLen);
		}
		return fileByte;
	}
	
    /**
     * 对源数据进行摘要处理
     * @param plainText 源数据
     * @param algorithm 摘要算法
     * @param base64flag Base64处理开关
     * @return 摘要
     * @throws UnsupportedEncodingException 
     */
    public static String mdEncode(String plainText, String algorithm, boolean base64flag) throws UnsupportedEncodingException{
    	String encStr = "".intern();
    	try {
			MessageDigest md = MessageDigest.getInstance(algorithm);
			md.update(plainText.getBytes("UTF-8"));
			
			byte tmp[] = md.digest();
			
			char str[] = new char[16 * 2];
			int k = 0;
			for (int i = 0; i < 16; i++) {
				byte byte0 = tmp[i];
				str[k++] = hexDigits[byte0 >>> 4 & 0xf];
				str[k++] = hexDigits[byte0 & 0xf];
			}
			
			encStr = new String(str);
			logger.info("******encStr=".concat(encStr));
			
	    	if(base64flag){
				// Base64转换(用于BASE64编码重写无换行)
	    		String base64str = Base64Converter.encodeWithNoDLE(encStr.getBytes("UTF-8"));
	    		return base64str;
	    	}
		} catch (NoSuchAlgorithmException e) {
			logger.info(e.getMessage());
		}
    	
    	
    	return encStr;
    }
    
    /**
     * 对源数据进行摘要处理
     * @param plainBytes 源数据
     * @param algorithm 摘要算法
     * @param base64flag Base64处理开关
     * @return 摘要
     * @throws UnsupportedEncodingException 
     */
    public static String mdEncode(byte[] plainBytes, String algorithm, boolean base64flag) throws UnsupportedEncodingException{
    	String encStr = "".intern();
    	try {
			MessageDigest md = MessageDigest.getInstance(algorithm);
			md.update(plainBytes);
			
			byte tmp[] = md.digest();
			char str[] = new char[16 * 2];
			int k = 0;
			for (int i = 0; i < 16; i++) {
				byte byte0 = tmp[i];
				str[k++] = hexDigits[byte0 >>> 4 & 0xf];
				str[k++] = hexDigits[byte0 & 0xf];
			}
			encStr = new String(str);
			
	    	if(base64flag){
				// Base64转换(用于BASE64编码重写无换行)
	    		String base64str = Base64Converter.encodeWithNoDLE(encStr.getBytes("UTF-8"));
				return base64str;
	    	}
		} catch (NoSuchAlgorithmException e) {
			logger.info(e.getMessage());
		}
    	
    	return encStr;
    }
	/**
	 * 转化字符串为十六进制编码 
	 * @param s
	 * @return
	 */
    public static String toHexString(String s) 
    { 
        String str=""; 
	    for (int i=0;i<s.length();i++) 
	    { 
	    int ch = (int)s.charAt(i); 
	    String s4 = Integer.toHexString(ch); 
	    str = str + s4; 
	    } 
	    return str; 
    } 
  /**
   * 转化十六进制编码为字符串
   * @param s
   * @return
   */
    public static String toStringHex(String s) 
    { 
	    byte[] baKeyword = new byte[s.length()/2]; 
	    for(int i = 0; i < baKeyword.length; i++) 
	    { 
	    try 
	    { 
	    baKeyword[i] = (byte)(0xff & Integer.parseInt(s.substring(i*2, i*2+2),16)); 
	    } 
	    catch(Exception e) 
	    { 
	    e.printStackTrace(); 
	    } 
	    } 
	    try 
	    { 
	    s = new String(baKeyword, "utf-8");//UTF-16le:Not 
	    } 
	    catch (Exception e1) 
	    { 
	    e1.printStackTrace(); 
	    } 
	    return s; 
    } 
    
	public static void main(String[] args) throws UnsupportedEncodingException {
		String s = "RmVlMC4wMGFkZFBheUJvb2tGbGFnWWFwcFZlcnVuZGVmaW5lZC4xLjAuMGJrSWQ4MTFicmFuZFpURSBWOTc1Y2hrbWVzZ05jdXJyZW5jeVR5cGUwMWRJZDZjOjhiOjJmOmU5OmQxOmQ5ZFR5cDAyaXNDcmFjazBpc1dpZmlZbXNnQ2hrQ29kZTQ0ODYzNm9wSWRlYnVzX0lubmVyT3RoZXJUcmFuc2Zlcm9zVmVyQVJELjQuMi4ycGFzc3dvcmQxMjMxMjNwYXlBY2NvdW50ODExMDUwMTk5MDAwMDAwMjQ3cGF5QWNjb3VudE5hbWXpo57miaxwYXlBY2NvdW50T3Blbk5vZGU4MTEwMTA1MDFwYXlBbW91bnQxLjAwcGF5VXNl5omL5py66ZO26KGM6L2s6LSmcmVjQWNjb3VudDYyMjk3MjAxMDEwMDI1MTMzMTlyZWNBY2NvdW50TmFtZeiLueaenHJlY0FjY291bnRPcGVuQmFua+azsOWuieW4guWVhuS4mumTtuihjOiCoeS7veaciemZkOWFrOWPuOiQpeS4mumDqHJlY0JhbmtUeXBlMHJlY01vYmlsZTEzOTUzODE3NjU2cnFJZDAxcnNwRm10anNvbnNhZmVUeXBlMDJzaWRIU0pGRlJEQkJGQVhDV0ZKRUZBRUJZRUtDWENZQVVEWERaR0dEUUlVc24yMDEzMTAyNzE4MTg1NjUwODZjOjhiOjJmOmU5OmQxOmQ5c3RpbWUyMDEzMTAyNzE4MTg1NjUwOHRyYW5zSWQxMDIwMjI=";
		mdEncode(s, "SHA1", true);
	}
}
